<template>
 <el-dialog v-model="$store.state.IsRestPassword" title="修改密码" width="600" @before-close="handleClose">
    <div class="app-resetPassword">
      <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="200px"
      
      status-icon
    >
      <el-form-item label="旧密码" prop="currentPassword">
        <el-input v-model="ruleForm.currentPassword" />
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="ruleForm.newPassword" />
      </el-form-item>
      <el-form-item label="再次输入新密码" prop="confirmPassword">
        <el-input v-model="ruleForm.confirmPassword" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          修改
        </el-button>
      </el-form-item>
    </el-form>
    </div>
 </el-dialog>
</template>

<script lang="ts" setup>
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { restPassword } from '@/server/center'
import { ElMessage } from 'element-plus'
//路由
const router = useRouter()
//状态vuex
const store = useStore()
//定义属性
interface RuleForm {
  currentPassword:string,
  newPassword:string,
  confirmPassword: string
}
//开关
const dialogTableVisible = ref(true)
//表单
const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
  currentPassword:'',
  confirmPassword:'',
  newPassword:''
})
const validatePassword = (rule: any, value: any, callback: any) => {
  if (ruleForm.newPassword !==  ruleForm.confirmPassword) {
      return callback(new Error('两次输入的密码不一致'))
  }else{
      return callback()
  }
}
const rules = reactive<FormRules<RuleForm>>({
  currentPassword: [
    { required: true, message: '请输入旧密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度需要6-20', trigger: 'blur' },
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度需要6-20', trigger: 'blur' },
  ],
  confirmPassword:[
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { validator: validatePassword, trigger: 'blur' }
  ]
})



const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      handleRestPassword()
    } else {
      console.log('error submit!', fields)
    }
  })
}
const handleRestPassword=async ()=>{
    try{
      await restPassword(ruleForm)
      ElMessage.success("修改成功")
    } catch(err){
      ElMessage.error("修改失败")
    }
}
const handleClose=()=>{
  store.commit('changRestPassword',false)
}

</script>
<style lang="scss" scoped>
  .app-restPassword{
    
  }
</style>